package cn.csust.net2.manager.client.Interaction;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.csust.net2.manager.client.app.App;
import cn.csust.net2.manager.client.ux.ExpandTree;
import cn.csust.net2.manager.shared.po.InnerMail;
import cn.csust.net2.manager.shared.po.PO;
import cn.csust.net2.manager.shared.po.Student;
import cn.csust.net2.manager.shared.po.User;
import cn.csust.net2.manager.shared.service.ByGradeService;
import cn.csust.net2.manager.shared.service.ByGradeServiceAsync;
import cn.csust.net2.manager.shared.service.InnerMailService;
import cn.csust.net2.manager.shared.service.InnerMailServiceAsync;
import cn.csust.net2.manager.shared.vo.Config;
import cn.csust.net2.manager.shared.vo.TreeNode;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
 * 
 * 站内信窗口
 * @author Administrator
 *
 */
public class MailWriteWindow extends Window{
	
	private ByGradeServiceAsync service ;
	private InnerMailServiceAsync mailService;
	
	private ExpandTree treePanel;
	
	private FormPanel panel;
	
	List<User> receiverList;
	private User receiver;
	
	private TextField<String> titleFiled;
	private TextField<String> receiverField;
	private HtmlEditor content ;
	
	public MailWriteWindow(){	
		this.setSize(600, 500);
		this.setLayout(new BorderLayout());
		this.setLayoutOnChange(true);
		init();
	}
	void init(){
		receiverList = new ArrayList<User>();

		service = GWT.create(ByGradeService.class);
		mailService =  GWT.create(InnerMailService.class);
		
		
		
		panel = new FormPanel();   
	    panel.setBorders(false);   
	    panel.setBodyBorder(false);   
	    panel.setLabelWidth(55);   
	    panel.setPadding(5);   
		panel.setHeaderVisible(false); 
		panel.setLayoutOnChange(true);
		  
	    titleFiled = new TextField<String>();    
	    titleFiled.setFieldLabel("主题");   
	    panel.add(titleFiled); 
	   
	    receiverField = new TextField<String>(); 
	    receiverField.setReadOnly(true);
	    receiverField.setFieldLabel("接收人");   
	    panel.add(receiverField); 
	  
	    content = new HtmlEditor(); 
	    content.setReadOnly(true);
	    content.setHideLabel(true);
	    panel.add(content, new FormData("100% -53")); 
	    

		Button send = new Button("发送");
	    send.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				if(!validate()){
					return;
				}
				InnerMail innerMail = new InnerMail();
				innerMail.setTitle(titleFiled.getValue());
				innerMail.setSender(App.getUser());
				innerMail.setInnerMailContent(content.getValue());
				innerMail.setSendDate(new Date());
				if(!receiverList.isEmpty()){
					try {
						for(User r: receiverList){
							innerMail.setReceiver(r);
							mailService.save(innerMail,new  AsyncCallback<Void>() {
								
								@Override
								public void onSuccess(Void result) {
									// TODO Auto-generated method stub
									
								}
								
								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									
								}
							});

						}
						MessageBox.alert("消息", "发送成功", null);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						MessageBox.alert("消息", "发送失败", null);
						e.printStackTrace();
					}
				}
				

			}	    	
	    });
	    Button reset = new Button("重置");
	    reset.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				titleFiled.setValue("");
				receiverField.setValue("");
				content.setValue("");
				
				receiverList.clear();
			}
	    	
	    });
		panel.addButton(send);
		panel.addButton(reset);
	    BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);   
	    centerData.setMargins(new Margins(0));   	    
	    this.add(panel,centerData); 
	    
	}
	
	
	private void initTree(){
		Map <String ,Object> map = new HashMap<String , Object>();
		map.put(ExpandTree.TEACHER_ADD, false);
		treePanel = new ExpandTree(Student.class,map){
			@Override
			protected void load(Object loadConfig,Map<String,Object> configs,AsyncCallback<List<TreeNode>> callback) {
				
				service.getChildren((TreeNode)loadConfig,configs, callback);
			}

			@Override
			protected void load(String[] items) {
				
				Config c = new Config();
				c.put(ExpandTree.GRADE_ITEMS, items);
				treePanel.load(Student.class,c);
			}
		};
		treePanel.getTree().addListener(Events.OnDoubleClick, new Listener<TreePanelEvent<BeanModel>>(){

			@Override
			public void handleEvent(TreePanelEvent<BeanModel> be) {
				// TODO Auto-generated method stub
				PO bm = be.getItem().getBean();
				if(bm instanceof User){
					User re = (User)bm ;
					receiverList.add(re);
					if(receiverField.getValue()==null){
						receiverField.setValue(re.getName()+"<"+re.getUserID()+">");
					}else{
						receiverField.setValue(receiverField.getValue()+";"+re.getName()+"<"+re.getUserID()+">");
					}
				}else{
					System.out.println("it is not user'instance");
				}
				
			}
			 
		});
	}
	
	public void recreateWindow(){
		
		Button removeReceivers = new Button("清空接受人");
		removeReceivers.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				receiverList.clear();
				receiverField.setValue(null);
			}
			
		});
		panel.addButton(removeReceivers);
		initTree();
		
		BorderLayoutData eastData = new BorderLayoutData(LayoutRegion.EAST, 200);  
		this.add(treePanel, eastData);
	}
   
	//基本验证
	private boolean validate(){
		if(titleFiled.getValue()==null||titleFiled.getValue().trim()==""){
			MessageBox.alert("消息", "主题不能为空", null);
			return false;
		}else if(receiverList.size()==0){
			MessageBox.alert("消息", "没有选择发送人", null);
			return false;
		}else{
			return true;
		}
	}
	public User getReceiver() {
		return receiver;
	}
	public void setReceiver(User receiver) {
		this.receiver = receiver;
		receiverList.add(receiver);
		receiverField.setValue(receiver.getName()+"<"+receiver.getUserID()+">");
	}
	public FormPanel getPanel() {
		return panel;
	}
	public void setPanel(FormPanel panel) {
		this.panel = panel;
	}
	
	
}
